<?php
/**
*+-------APP 用户模型--------+
*+-------------------------------------------------+
*+------------进行用户业务操作操作---------------+
*+-------------------------------------------------+
*+-@author susy.liang <liangling@ilongyuan.com.cn>-+
*+-------------------------------------------------+
*/
namespace Api\Model;
use Think\Model;
use User\Api\UserApi;

class MemberModel extends Model{
    
    //自动验证
    protected $_validate = array(
        array('nickname', '1,10', '昵称长度为1-10个字符', self::VALUE_VALIDATE, 'length'),
        array('nickname', '', '昵称被占用', self::VALUE_VALIDATE, 'unique'),
    );

    /* 用户模型自动完成 */
    protected $_auto = array(
        array('login', 0, self::MODEL_INSERT),
        array('type', 2, self::MODEL_BOTH),
        array('status', 1, self::MODEL_BOTH),
    );

    /**
     * 登录指定用户
     * @param  integer $uid 用户ID
     * @return boolean      ture-登录成功，false-登录失败
     */
    public function login($uid){
        $user = $this->field(true)->find($uid);
        if(!$user){ //未注册
            /* 在当前应用中注册用户 */
        	$Api = new UserApi();
        	$info = $Api->info($uid);
            $user = $this->create(array('status' => 1, 'type'=>2));
            $user['uid'] = $uid;
            $user['referral'] = $this->createUserReferral($user);
            if(!$this->add($user)){
                $this->error = '前台用户信息注册失败，请重试！';
                return false;
            }
        } elseif(1 != $user['status']) {
            $this->error = '用户未激活或已禁用！'; //应用级别禁用
            return false;
        }elseif (2 != $user['type']) {
            $this->error = '非前台用户';
            return false;
        }

        $user['login'] = array('exp', '`login`+1');
        $user['last_login_time'] = NOW_TIME;
        $user['last_login_ip'] = get_client_ip(1);
        if (!$user['referral'])
        {
            $user['referral'] = $this->createUserReferral($user);
        }
        $this->save($user);

        return true;
    }

    /**
    *新增用户
    */
    public function register($data){
        $data = $this->create($data);
        if(!$data)
            return false;
        $data['referral'] = $this->createUserReferral($data);
        if($this->add($data))
            return true;
        else
            return false;
    }

    // 生成16位用户推广码 根据uid做md5
    protected function createUserReferral($data)
    {
        return substr( md5($data['uid'] . NOW_TIME . rand(1000,9999)), 8, 16 );
    }

}
